﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CoreEx.DynamicInvoker;
using LinFu.IoC.Configuration;
using LinFu.IoC.Interfaces;
using LinFu.IoC;

namespace CoreEx.Database.Persistence.Implementation
{
    public class Persister : IPersister, IInitialize
    {
        private IServiceContainer _serviceContainer; 
        
        public void Persist(IList<IObjectState> changeRequests)
        {
         
            var comparer = _serviceContainer.GetService<IComparer<IObjectState>>();
            var orderedChangeRequests = changeRequests.OrderBy(cr => cr);


            var persistMethod = typeof (IObjectPersister<>).GetMethod("Persist");
            foreach (var objectState in orderedChangeRequests)
            {
                var genericObjectPersisterType =
                    typeof (IObjectPersister<>).MakeGenericType(objectState.Target.GetType());

                var objectPersister = _serviceContainer.GetService(genericObjectPersisterType);

                persistMethod.DynamicInvoke(objectPersister, objectState);
            }

            
            
        }

        public void Initialize(IServiceContainer source)
        {
            _serviceContainer = source;
        }
    }
}
